<?php
/**
 * User: Drery
 * Date: 2015/12/18
 * Time: 10:34
 */

namespace backend\controllers;

use backend\components\SubLevelAccess;
use backend\models\AdminPasswordForm;
use backend\models\Role;
use backend\models\UserRole;
use common\models\District;
use Yii;
use backend\models\Admin;
use yii\data\ActiveDataProvider;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;

class AdminController extends InitController
{
    /**
     * @var Admin
     */
    public $model;

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['levelAuth'] = [
            'class' => AccessControl::className(),
            'only' => ['role', 'forbid', 'password'],
            'rules' => [
                [
                    'class' => SubLevelAccess::className(),
                    'allow' => true
                ]
            ]
        ];
        return $behaviors;
    }

    public function getCurrentDistrict()
    {
        /** @var Admin $model */
        $model = Admin::find()->where(['id'=>Yii::$app->request->get('id')])->one();
        if (!$model)
            throw new NotFoundHttpException();
        $this->model = $model;
        return $model->relate_id;
    }

    public function actionIndex()
    {
        $query = Admin::find()->andWhere(['!=', 'user_name', 'root'])->with('roles');
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 50,
            ],
            'sort' => [
                'attributes' => [
                    'create_time' => [
                        'asc' => ['create_time' => SORT_ASC],
                        'desc' => ['create_time' => SORT_DESC]
                    ]
                ]
            ]
        ]);
        if (Yii::$app->user->identity->user_name != 'root') {
            $query->andWhere(['in', 'relate_id', District::recursiveSubs(Yii::$app->user->identity->relate_id, Yii::$app->user->identity->level)]);
        }
        return $this->render('index', [
            'dataProvider' => $dataProvider
        ]);
    }

    public function actionAdd()
    {
        $model = new Admin(['scenario' => 'add']);
        if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
            if ($model->save()) {
                return $this->redirect('index');
            }
        }
        $roleList = Role::find()->where(['!=', 'title', '角色管理'])->all();
        return $this->render('add', [
            'model' => $model,
            'roleList' => ArrayHelper::map($roleList, 'id', 'title')
        ]);
    }

    public function actionRole()
    {
        $id = Yii::$app->request->get('id');
        $model = UserRole::find()->where(['admin_user_id' => $id])->one();
        if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
            if ($model->save()) {
                return $this->redirect('index');
            }
        }
        $roleList = Role::find()->where(['!=', 'title', '角色管理'])->all();
        return $this->render('role', [
            'model' => $model,
            'roleList' => ArrayHelper::map($roleList, 'id', 'title')
        ]);
    }

    public function actionPassword()
    {
        $adminModel = $this->model;
        $model = new AdminPasswordForm();
        if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
            if ($model->execute($adminModel) !== false) {
                Yii::$app->session->setFlash('修改密码成功！');
                return $this->redirect('index');
            }
            Yii::$app->session->setFlash('修改密码失败，请重试！');
        }
        return $this->render('password', [
            'model' => $model
        ]);
    }

/*    public function actionUpdate()
    {
        $id = Yii::$app->request->get('id');
        $model = Admin::find()->where(['id' => $id])->one();
        if (Yii::$app->request->isPost) {
            $posts = Yii::$app->request->post('Admin');
            $model->relate_id = $posts['relate_id'];
            if ($model->save(false)) {
                return $this->redirect('index');
            }
        }

        return $this->render('update', [
            'model' => $model
        ]);
    }*/

    public function actionForbid()
    {
        $model = $this->model;
        if (Yii::$app->request->isPost) {
            $model->is_forbidden = abs($model->is_forbidden - 1);
            if ($model->save(false)) {
                return $this->redirect('index');
            }
        }

        return $this->render('update', [
            'model' => $model
        ]);
    }
}